package com.xxjqr.rbac.converter;

import com.baomidou.mybatisplus.core.enums.IEnum;
import com.xxjqr.rbac.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;

public class StringToEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    private static final Map<Class, Converter> CONVERTERS = new HashMap<>();

    /**
     * 从转换器工厂中找到对应的转换器返回
     * @param targetType 转换后的类型
     * @return 返回一个转化器
     */
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        StringToEnumConverter converter = (StringToEnumConverter) CONVERTERS.get(targetType);
        if (converter == null) {
            converter = new StringToEnumConverter(targetType);
            CONVERTERS.put(targetType, converter);
        }
        return converter;
    }

}
